<?php

namespace app\api\controller\wddj;

use app\api\controller\wddj\BaseController;
use app\common\model\wddj\UserVehicles;
use app\common\model\wddj\VehicleBrands;
use think\Db;
use think\Exception;

/**
 * 乘客车辆管理控制器
 */
class Vehicle extends BaseController
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 获取车辆列表
     */
    public function list()
    {
        try {
            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('请先登录'));
            }

            // 直接使用Db类查询
            $list = Db::name('wddj_user_vehicles')->alias('uv')
                ->join('wddj_vehicle_brands vb', 'uv.vehicle_brand_id = vb.id', 'LEFT')
                ->where('uv.wechat_id', $user->id)
                ->where('uv.status', 1)
                ->field('uv.*, vb.brand_name')
                ->order('uv.is_default desc, uv.id desc')
                ->select();

            $data = [];
            foreach ($list as $item) {
                $data[] = [
                    'id' => $item['id'],
                    'license_plate' => $item['license_plate'],
                    'vehicle_type' => $item['vehicle_type'],
                    'vehicle_brand_id' => $item['vehicle_brand_id'],
                    'brand_name' => $item['brand_name'] ?? '',
                    'vehicle_model' => $item['vehicle_model'],
                    'vehicle_color' => $item['vehicle_color'],
                    'is_default' => $item['is_default'],
                    'front_image' => $item['front_photo'],
                    'side_image' => $item['side_photo'],
                    'createtime' => date('Y-m-d H:i:s', $item['createtime'])
                ];
            }

            $this->success(__('获取成功'), ['list' => $data]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取车辆详情
     */
    public function detail()
    {
        try {
            $id = $this->request->request('id');
            if (!$id) {
                $this->error(__('参数错误'));
            }

            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('请先登录'));
            }

            // 直接查询车辆信息
            $vehicle = Db::name('wddj_user_vehicles')->alias('uv')
                ->join('wddj_vehicle_brands vb', 'uv.vehicle_brand_id = vb.id', 'LEFT')
                ->where('uv.id', $id)
                ->where('uv.wechat_id', $user->id)
                ->where('uv.status', 1)
                ->field('uv.*, vb.brand_name')
                ->find();

            if (!$vehicle) {
                $this->error(__('车辆不存在'));
            }

            // 调整字段名称，前端使用front_image和side_image
            $data = [
                'id' => $vehicle['id'],
                'license_plate' => $vehicle['license_plate'],
                'vehicle_type' => $vehicle['vehicle_type'],
                'vehicle_brand_id' => $vehicle['vehicle_brand_id'],
                'brand_name' => $vehicle['brand_name'],
                'vehicle_model' => $vehicle['vehicle_model'],
                'vehicle_color' => $vehicle['vehicle_color'],
                'is_default' => $vehicle['is_default'],
                'front_image' => $vehicle['front_photo'],
                'side_image' => $vehicle['side_photo']
            ];

            $this->success(__('获取成功'), $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 添加车辆
     */
    public function add()
    {
        try {
            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('请先登录'));
            }

            \think\Log::write('当前用户信息: ' . json_encode($user), 'info');

            $data = $this->request->only([
                'license_plate',
                'vehicle_type',
                'vehicle_brand_id',
                'vehicle_model',
                'vehicle_color',
                'is_default',
                'front_image',
                'side_image'
            ]);

            \think\Log::write('接收到的车辆数据: ' . json_encode($data), 'info');

            // 验证必填字段
            if (empty($data['license_plate'])) {
                $this->error(__('请输入车牌号码'));
            }
            if (empty($data['vehicle_type'])) {
                $this->error(__('请选择车辆类型'));
            }
            if (empty($data['vehicle_brand_id'])) {
                $this->error(__('请选择车辆品牌'));
            }
            if (empty($data['vehicle_model'])) {
                $this->error(__('请输入车型型号'));
            }
            if (empty($data['vehicle_color'])) {
                $this->error(__('请输入车辆颜色'));
            }

            // 检查车牌号是否已存在
            $exists = Db::name('wddj_user_vehicles')
                ->where('license_plate', $data['license_plate'])
                ->where('wechat_id', $user->id)
                ->where('status', 1)
                ->find();

            if ($exists) {
                $this->error(__('该车牌号已存在'));
            }

            Db::startTrans();
            try {
                // 如果设为默认，先取消其他默认车辆
                if (isset($data['is_default']) && $data['is_default'] == 1) {
                    Db::name('wddj_user_vehicles')
                        ->where('wechat_id', $user->id)
                        ->where('is_default', 1)
                        ->update(['is_default' => 0]);
                }

                // 修正图片字段名称
                $insertData = [
                    'wechat_id' => $user->id,
                    'license_plate' => $data['license_plate'],
                    'vehicle_type' => $data['vehicle_type'],
                    'vehicle_brand_id' => $data['vehicle_brand_id'],
                    'vehicle_model' => $data['vehicle_model'],
                    'vehicle_color' => $data['vehicle_color'],
                    'is_default' => isset($data['is_default']) ? $data['is_default'] : 0,
                    'status' => 1,
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                // 前端传来的是front_image和side_image，数据库是front_photo和side_photo
                if (isset($data['front_image'])) {
                    $insertData['front_photo'] = $data['front_image'];
                }
                
                if (isset($data['side_image'])) {
                    $insertData['side_photo'] = $data['side_image'];
                }

                \think\Log::write('准备插入的完整数据: ' . json_encode($insertData), 'info');

                // 直接使用Db类插入数据
                $insertId = Db::name('wddj_user_vehicles')->insertGetId($insertData);

                \think\Log::write('插入ID: ' . $insertId, 'info');

                if (!$insertId) {
                    throw new Exception('添加失败');
                }

                // 验证是否真的插入了
                $inserted = Db::name('wddj_user_vehicles')
                    ->where('id', $insertId)
                    ->find();
                
                \think\Log::write('插入后查询结果: ' . json_encode($inserted), 'info');

                Db::commit();
                $this->success(__('添加成功'));
            } catch (Exception $e) {
                Db::rollback();
                \think\Log::write('添加车辆失败: ' . $e->getMessage(), 'error');
                throw $e;
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 编辑车辆
     */
    public function edit()
    {
        try {
            $id = $this->request->request('id');
            if (!$id) {
                $this->error(__('参数错误'));
            }

            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('请先登录'));
            }

            \think\Log::write('编辑车辆 - 当前用户信息: ' . json_encode($user), 'info');

            $vehicle = Db::name('wddj_user_vehicles')
                ->where('id', $id)
                ->where('wechat_id', $user->id)
                ->where('status', 1)
                ->find();

            if (!$vehicle) {
                $this->error(__('车辆不存在'));
            }

            $data = $this->request->only([
                'license_plate',
                'vehicle_type',
                'vehicle_brand_id',
                'vehicle_model',
                'vehicle_color',
                'is_default',
                'front_image',
                'side_image'
            ]);

            \think\Log::write('编辑车辆 - 接收到的数据: ' . json_encode($data), 'info');

            // 验证必填字段
            if (empty($data['license_plate'])) {
                $this->error(__('请输入车牌号码'));
            }
            if (empty($data['vehicle_type'])) {
                $this->error(__('请选择车辆类型'));
            }
            if (empty($data['vehicle_brand_id'])) {
                $this->error(__('请选择车辆品牌'));
            }
            if (empty($data['vehicle_model'])) {
                $this->error(__('请输入车型型号'));
            }
            if (empty($data['vehicle_color'])) {
                $this->error(__('请输入车辆颜色'));
            }

            // 检查车牌号是否已存在（排除当前车辆）
            $exists = Db::name('wddj_user_vehicles')
                ->where('license_plate', $data['license_plate'])
                ->where('wechat_id', $user->id)
                ->where('id', 'neq', $id)
                ->where('status', 1)
                ->find();

            if ($exists) {
                $this->error(__('该车牌号已存在'));
            }

            Db::startTrans();
            try {
                // 如果设为默认，先取消其他默认车辆
                if (isset($data['is_default']) && $data['is_default'] == 1) {
                    Db::name('wddj_user_vehicles')
                        ->where('wechat_id', $user->id)
                        ->where('id', 'neq', $id)
                        ->where('is_default', 1)
                        ->update(['is_default' => 0]);
                }

                // 修正图片字段名称
                $updateData = [
                    'license_plate' => $data['license_plate'],
                    'vehicle_type' => $data['vehicle_type'],
                    'vehicle_brand_id' => $data['vehicle_brand_id'],
                    'vehicle_model' => $data['vehicle_model'],
                    'vehicle_color' => $data['vehicle_color'],
                    'is_default' => isset($data['is_default']) ? $data['is_default'] : 0,
                    'updatetime' => time()
                ];
                
                // 前端传来的是front_image和side_image，数据库是front_photo和side_photo
                if (isset($data['front_image'])) {
                    $updateData['front_photo'] = $data['front_image'];
                }
                
                if (isset($data['side_image'])) {
                    $updateData['side_photo'] = $data['side_image'];
                }

                \think\Log::write('编辑车辆 - 准备更新的数据: ' . json_encode($updateData), 'info');

                $result = Db::name('wddj_user_vehicles')
                    ->where('id', $id)
                    ->update($updateData);

                \think\Log::write('编辑车辆 - 更新结果: ' . $result, 'info');

                if ($result === false) {
                    throw new Exception('修改失败');
                }

                Db::commit();
                $this->success(__('修改成功'));
            } catch (Exception $e) {
                Db::rollback();
                \think\Log::write('编辑车辆失败: ' . $e->getMessage(), 'error');
                throw $e;
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 删除车辆
     */
    public function delete()
    {
        try {
            $id = $this->request->request('id');
            if (!$id) {
                $this->error(__('参数错误'));
            }

            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('请先登录'));
            }

            $vehicle = UserVehicles::where('id', $id)
                ->where('wechat_id', $user->id)
                ->where('status', 1)
                ->find();

            if (!$vehicle) {
                $this->error(__('车辆不存在'));
            }

            // 软删除车辆
            $result = $vehicle->save(['status' => 0, 'updatetime' => time()]);

            if ($result === false) {
                $this->error(__('删除失败'));
            }

            $this->success(__('删除成功'));
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 设为默认车辆
     */
    public function setDefault()
    {
        try {
            $id = $this->request->request('id');
            if (!$id) {
                $this->error(__('参数错误'));
            }

            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('请先登录'));
            }

            $vehicle = UserVehicles::where('id', $id)
                ->where('wechat_id', $user->id)
                ->where('status', 1)
                ->find();

            if (!$vehicle) {
                $this->error(__('车辆不存在'));
            }

            Db::startTrans();
            try {
                // 先取消其他默认车辆
                UserVehicles::where('wechat_id', $user->id)
                    ->where('is_default', 1)
                    ->update(['is_default' => 0]);

                // 设置当前车辆为默认
                $result = $vehicle->save(['is_default' => 1, 'updatetime' => time()]);

                if ($result === false) {
                    throw new Exception('设置失败');
                }

                Db::commit();
                $this->success(__('设置成功'));
            } catch (Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取车辆品牌列表
     */
    public function getBrandList()
    {
        try {
            // 添加调试信息
            \think\Log::write('开始获取车辆品牌列表', 'info');
            
            $list = VehicleBrands::where('status', 'normal')
                ->order('weigh asc, id desc')
                ->field('id,brand_name as name')
                ->select();

            // 直接使用查询结果，不需要转换
            $list = $list ?: [];
            
            \think\Log::write('品牌列表查询结果: ' . json_encode($list), 'info');
            
            $this->success(__('获取成功'), $list);
        } catch (Exception $e) {
            \think\Log::write('获取品牌列表失败: ' . $e->getMessage(), 'error');
            $this->error($e->getMessage());
        }
    }

    /**
     * 测试用户登录状态
     */
    public function testUser()
    {
        try {
            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            \think\Log::write('收到的token: ' . $token, 'info');
            
            $user = $this->auth->getUser();
            if (!$user) {
                $this->error(__('请先登录'));
            }
            
            // 输出用户信息
            $data = [
                'user_id' => $user->id,
                'username' => $user->username,
                'nickname' => $user->nickname,
                'user_data' => $user->toArray()
            ];
            
            \think\Log::write('用户信息: ' . json_encode($data), 'info');
            
            $this->success(__('获取成功'), $data);
        } catch (Exception $e) {
            \think\Log::write('测试用户失败: ' . $e->getMessage(), 'error');
            $this->error($e->getMessage());
        }
    }
} 